/**
 * RegistryServerConfigHandler.java
 */
package fss.core.config;


import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

/**
 * The handler for parsing the RegistryServerConfig element from the configuration file.
 * 
 * @author thinh
 *
 */
class ServiceRegistryConfigHandler extends DefaultHandler {
    /**
     * The root tag for this handler.
     */
    private static final String ROOT_TAG = "ServiceRegistry";
    /**
     * The port tag.
     */
    private static final String PORT_TAG = "port";
    /**
     * The hostname tag.
     */
    private static final String HOSTNAME_TAG = "hostname";
    /**
     * The internal parsing buffer.
     */
    private StringBuilder buffer = new StringBuilder(512);
    /**
     * The flag to set when the root tag is encountered.
     */
    private boolean match = false;
    /**
     * The wrapped config object for this handler.
     */
    private ServiceRegistryConfig config = null;
    
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        // reset the buffer to parse the next element
        buffer.setLength(0);
        if(ROOT_TAG.equals(qName)) {
            match = true;
            config = new ServiceRegistryConfig();
        } else if(PORT_TAG.equals(qName) || HOSTNAME_TAG.equals(qName)) {
            match = true;
        }
    }
    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if(!match) return;
        if(PORT_TAG.equals(qName)) {
            try {
                config.addPort(Integer.parseInt(buffer.toString()));
            } catch(NumberFormatException e) {
                throw new SAXException("Error setting the RegistryServerConfig port: " + buffer.toString(), e);
            }
        } else if(HOSTNAME_TAG.equals(qName)) {
            config.addHost(buffer.toString());
        } 
    }
    @Override
    public void characters(char ch[], int start, int length) throws SAXException {
        buffer.append(ch, start, length);
    }
    /**
     * Get the wrapped config object.
     * @return the Registry Server Configuration.
     */
    public ServiceRegistryConfig getConfig() {
        return config;
    }
}
